
/***********************************************************************
 * InteractionLoop class
 * 
 * The main interaction loop of the game, which executes player commands
 *
 * Signature:
 *  public static InteractionLoop create();
 *  public void registerCommand (Command c);
 *  public void run ();
 ***********************************************************************/


import java.io.*;

public class InteractionLoop {

    private List<Observer<String>> observers;

    private List<Command> commands;

    private InteractionLoop () {
        commands = List.empty();
    }

    public static InteractionLoop create() {
        return new InteractionLoop();
    }

    public void registerCommand (Command c) {
	commands = List.cons(c,commands);
    }

    private Option<Command> findCommand (String cname) {
	for (Command c : commands) 
	    if (c.name().equals(cname))
		return Option.some(c);
	return Option.none();
    }

    private String getInput () {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String response = "";
    
        try {
            response = br.readLine();
            if (response==null) {
                return "";
            }
        } catch (IOException ioe) {
            System.out.println("IO error reading from terminal\n");
            System.exit(1);
        }
        return response;
    }


    public void run () {

        String response;
	Option<Command> comm;
	String[] splitResponse;
        while (true) {
            System.out.print("\n> ");
	    // split input into different bits
	    response = getInput();
	    splitResponse = response.split ("\\s++");
	    if (response.equals("") || splitResponse.length==0) 
		continue;
	    if (splitResponse[0].equals("?")) {
		System.out.println("Known commands:");
		for (Command c : commands)
		    System.out.println("  " + c.name());
		continue;
	    }
	    comm = findCommand(splitResponse[0]);
	    if (comm.isNone()) {
		System.out.println("Unknown command -- " + splitResponse[0]);
		continue;
	    }
	    if (comm.valOf().execute(splitResponse))
		SpaceGame.clock().tick();
        }
    }


}
